package com.jinyijia.admin.interfaces;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyijia.admin.config.Constant;
import com.jinyijia.admin.interfaces.dto.AccountEnableDTO;
import com.jinyijia.admin.interfaces.utils.HttpHeadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import java.security.Principal;

/**
 * Created by yangrd on 2018/3/9
 **/
@RestController
@RequestMapping(Constant.Path.ACCOUNTS)
public class AccountController {

    @Autowired
    private RestOperations restOperations;

    @Value("${jinYiJia.api.accounts}")
    private String apiPath;

    @PostMapping
    public ResponseEntity save(@RequestBody JSONObject jsonObject) {
        return restOperations.postForEntity(apiPath, jsonObject, JSONObject.class);
    }

    @PutMapping("/{id}/reset-pwd")
    public ResponseEntity restPwd(@PathVariable Long id){
        restOperations.put(apiPath+"/"+id+"/reset-pwd",null);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/change-current-user-pwd")
    public ResponseEntity changeCurrentUserPwd(Principal currentUser, @RequestBody JSONObject jsonObject){
        jsonObject.put("name",currentUser.getName());
        String response = restOperations.exchange(apiPath+"/change-current-user-pwd", HttpMethod.PUT, HttpHeadUtil.addBody(jsonObject), String.class).getBody();
        return ResponseEntity.ok(response);
    }

    @PutMapping
    public ResponseEntity changeStatus(@RequestBody AccountEnableDTO accountEnableDTO) {
        restOperations.put(apiPath, accountEnableDTO);
        return ResponseEntity.ok("ok");
    }

    @GetMapping("/name")
    public ResponseEntity findIdAndName(@RequestParam(defaultValue = "") String name) {
        return restOperations.getForEntity(apiPath + "/queryName?name=" + name, JSONArray.class);
    }

    @GetMapping
    public ResponseEntity findAll(@RequestParam(value = "name", defaultValue = "", required = false) String name,
                                  @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        JSONObject object = restOperations.getForObject(apiPath + "?name=" + name + "&page=" + page + "&size=" + size, JSONObject.class);
        return ResponseEntity.ok(object);
    }

}
